package com.daisuxia.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.service.ILianLianService;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.dao.IUserBankDao;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.service.IBackConfigParamsService;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IUserBankService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.HttpUtil;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.encrypt.AESUtil;

import redis.clients.jedis.JedisCluster;

@Controller
@RequestMapping(value = "/lianlianBindCard360")
public class LianLianBindCard360Controller extends BaseController {
    Logger logger = Logger.getLogger(getClass());

    @Autowired
    private ILianLianService lianlianService;
    @Autowired
    private IUserService userService;
    @Autowired
    private JedisCluster jedisCluster;
    @Autowired
    private IUserBankService userBankService;
    @Autowired
    private IBorrowOrderService borrowOrderService;
    
    @Autowired
	IBackConfigParamsService backConfigParamsService;
    
    @Autowired
    @Qualifier("userBankDaoImpl")
    IUserBankDao userBankDao;
    /**
     * 获取lianlian token（发送短信验证码功能）
     *
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "getLianLianToken")
    public void getLianLianToken(HttpServletRequest request, HttpServletResponse response, Model model) {
        String LIANLIAN_TOKEN_TOKEN = "LIANLIAN_TOKEN_TOKEN_"; // 生成手机认证码频繁标识key
        String telephone = request.getParameter("mobilePhone");
        Map<String, Object> retMap = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "绑定失败";
        String orderNo = "";
        try {
        	String userId = request.getParameter("userId");
        	User logUser = userService.searchByUserid(Integer.valueOf(userId));
            if (null == logUser) {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
                return;
            }
            Long remainTime = checkForFront(LIANLIAN_TOKEN_TOKEN, telephone, 60);
            if (remainTime > 0) {
                code = Status.FREQUENT.getName();
                retMap.put("time", remainTime);
                msg = "验证码请求频繁，请稍后重试";
                return;
            }
            User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
            if (null == user) {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
                return;
            }
            Integer checkResult = borrowOrderService.checkBorrow(Integer.parseInt(logUser.getId()));
            if (1 == checkResult) {
                msg = "您有借款申请正在审核或未还款完成，暂不能修改银行卡。";
                return;
            }
            if ((StringUtils.isBlank(user.getRealname())) || (!"1".equals(user.getRealnameStatus()))) {
                msg = "请填写个人信息";
                return;
            }
            Map<String, String> pams = this.getParameters(request);
            String phone = pams.get("phone") == null ? "" : pams.get("phone");
            String bankId = pams.get("bank_id") == null ? "" : pams.get("bank_id");
            String cardNo = pams.get("card_no") == null ? "" : pams.get("card_no");
            orderNo = pams.get("orderNo") == null ? "" : pams.get("orderNo");
            logger.info("phone:" + phone + ",bankId:" + bankId + ",cardNo:" + cardNo+",orderNo:"+orderNo);

            if (StringUtils.isBlank(phone)) {
                msg = "预留手机号码不能为空";
                return;
            }
            if (StringUtils.isBlank(bankId)) {
                msg = "银行不能为空";
                return;
            }
            if (StringUtils.isBlank(cardNo)) {
                msg = "银行卡号不能为空";
                return;
            }
            
            if(StringUtils.isBlank(orderNo)){
            	  msg = "orderNo不能为空";
                  return;
            }

            Map<String, String> tokenParaMap = new HashMap<String, String>();
            tokenParaMap.put("phone", phone.trim());
            tokenParaMap.put("bankId", bankId.trim());
            tokenParaMap.put("cardNo", cardNo.trim());
            tokenParaMap.put("userId", user.getId());
            tokenParaMap.put("actName", user.getRealname());
            tokenParaMap.put("idNo", user.getIdNumber());

            Map<String, Object> tokenRetMap = lianlianService.getBindCardToken(tokenParaMap);

            code = String.valueOf(tokenRetMap.get("code"));
            msg = String.valueOf(tokenRetMap.get("msg"));
     	  
     	   
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	 //调用推广平台
            String bind_status = "0000".equals(code)?"1":"2";
            if("2".equals(bind_status)){//失败的时候进行反馈
         	   invokeTgForBindCardFeedBack(orderNo, bind_status,msg);
            }
        	
            retMap.put("code", code);
            retMap.put("message", msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(retMap));
        }
    }


    /**
     * lianlian token 验证(确定绑卡功能)
     *
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "tokenValidate")
    public void tokenValidate(HttpServletRequest request, HttpServletResponse response, Model model) {
        String LIANLIAN_TO_TOKEN_VALIDATE = "LIANLIAN_TO_TOKEN_VALIDATE_"; // 生成手机认证码频繁标识key
        String telephone = request.getParameter("mobilePhone");
        Map<String, Object> retMap = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "绑定失败";
        try {
        	String userId = request.getParameter("userId");
        	User logUser = userService.searchByUserid(Integer.valueOf(userId));
            if (null == logUser) {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
                return;
            }
            Long remainTime = checkForFront(LIANLIAN_TO_TOKEN_VALIDATE, telephone);
            if (remainTime > 0) {
                code = Status.FREQUENT.getName();
                retMap.put("time", remainTime);
                msg = Status.FREQUENT.getValue();
                return;
            }
            User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
            if (null == user) {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
                return;
            }
            Integer checkResult = borrowOrderService.checkBorrow(Integer.parseInt(logUser.getId()));
            if (1 == checkResult) {
                msg = "您有借款申请正在审核或未还款完成，暂不能修改银行卡。";
                return;
            }
            if ((StringUtils.isBlank(user.getRealname())) || (!"1".equals(user.getRealnameStatus()))) {
                msg = "请填写个人信息";
                return;
            }
            Map<String, String> pams = this.getParameters(request);

            String token = jedisCluster.get("XJX_TOKEN_USERID" + user.getId());

            String verifyCode = pams.get("verify_code") == null ? "" : pams.get("verify_code");
            String phone = pams.get("phone") == null ? "" : pams.get("phone");
            String bankId = pams.get("bank_id") == null ? "" : pams.get("bank_id");
            String cardNo = pams.get("card_no") == null ? "" : pams.get("card_no");
            String orderNo = pams.get("orderNo") == null ? "" : pams.get("orderNo");
            

            logger.error("token:" + token + ",verifyCode:" + verifyCode+",orderNo:"+orderNo);

            if (StringUtils.isBlank(token)) {
                msg = "验证信息已过期，请稍后再试";
                return;
            }
            if (StringUtils.isBlank(phone)) {
                msg = "预留手机号码不能为空";
                return;
            }
            if (StringUtils.isBlank(bankId)) {
                msg = "银行不能为空";
                return;
            }
            if (StringUtils.isBlank(cardNo)) {
                msg = "银行卡号不能为空";
                return;
            }
            if (StringUtils.isBlank(verifyCode)) {
                msg = "短信验证码不能为空";
                return;
            }

            Map<String, String> tokenParaMap = new HashMap<String, String>();
            tokenParaMap.put("token", token.trim());
            tokenParaMap.put("userId", user.getId());
            tokenParaMap.put("verifyCode", verifyCode);
            tokenParaMap.put("phone", phone.trim());
            tokenParaMap.put("bankId", bankId.trim());
            tokenParaMap.put("cardNo", cardNo.trim());
            tokenParaMap.put("userId", user.getId());
            tokenParaMap.put("actName", user.getRealname());
            tokenParaMap.put("idNo", user.getIdNumber());

            Map<String, Object> tokenRetMap = lianlianService.bindCardValidate(tokenParaMap);

            code = String.valueOf(tokenRetMap.get("code"));
            msg = String.valueOf(tokenRetMap.get("msg"));
            
            String bind_status = "0000".equals(code)?"1":"2";
            
            //调用推广平台
    	   invokeTgForBindCardFeedBack(orderNo, bind_status,msg);
    	   retMap.put("handel", "no");
      		
        } catch (Exception e) {
            logger.error("lianlian token get error ", e);
        } finally {
            retMap.put("code", code);
            retMap.put("message", msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(retMap));
        }
    }


	private void invokeTgForBindCardFeedBack(String orderNo, String bind_status,String msg) {
		   HashMap<String, Object> params = new HashMap<String, Object>();
           params.put("syskey", "TG_SERVER_BK");
           List<BackConfigParams> list = backConfigParamsService.findParams(params);
           String postUrl =  list.get(0).getSysValue();
           
           postUrl = postUrl + "/rong/bindCardFeedBack";
          
           Map<String,String> paraMap = new HashMap<String,String>();
      	   paraMap.put("order_no", orderNo);
      	   paraMap.put("bind_status", bind_status);
      	   paraMap.put("reason", msg);
  		   String jsonString = JSONUtil.beanToJson(paraMap).toString();
  		
      		try {
      			System.out.println("postUrl:"+postUrl);
      			String ret = HttpUtil.getInstance().doPost(postUrl, jsonString);
      			System.out.print("ret:"+ret);
      			
      		} catch (IOException e) {
      			e.printStackTrace();
      		}
	}

    
    
    
    /**
     * 取消绑卡
     *
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "cancelBindCard")
    public void cancelBindCard(HttpServletRequest request, HttpServletResponse response, Model model) {
    	Map<String, Object> retMap = new HashMap<String, Object>();
    	String code="0000";
    	String msg="用户取消绑定";
    	try {  
    	  logger.error("cancelBindCard start");
    	  
    	  Map<String, String> pams = this.getParameters(request);
    	  
          String orderNo = pams.get("orderNo") == null ? "" : pams.get("orderNo");

          logger.error("orderNo:"+orderNo);

          String bind_status = "2";
            invokeTgForBindCardFeedBack(orderNo, bind_status,msg);

        } catch (Exception e) {
            logger.error("lianlian token get error ", e);
        } finally {
            retMap.put("code", code);
            retMap.put("message", msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(retMap));
        }
    }
    
    

    /**
     * 第一次绑定银行卡页面（进入绑卡页面）
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("credit-card/firstUserBank")
    public String firstUserBank(HttpServletRequest request, HttpServletResponse response, Model model) {
        List<Map<String, Object>> mapList = userBankService.findAllBankInfo();
        model.addAttribute("bankList", mapList);
        String signValue = request.getParameter("orderNo");
        String signValueDecrypt = AESUtil.decrypt(signValue, null);
        Map<String, Object> lianlianMap = JSONUtil.parseJSON2Map(signValueDecrypt);
        if (lianlianMap != null) {
			String userPhone = (String)lianlianMap.get("phone");
			String bankId = String.valueOf(lianlianMap.get("bankId"));
			String cardNo =  String.valueOf(lianlianMap.get("cardNo"));
			String userId =  String.valueOf(lianlianMap.get("userId"));
			String orderNo =  String.valueOf(lianlianMap.get("orderNo"));
			String return_url =  String.valueOf(lianlianMap.get("return_url"));
        	
			logger.error("firstUserBank return_url:"+return_url);
            UserCardInfo info = userService.findUserBankCard(Integer.parseInt(userId));
            
            Map<String,String> bankAllInfoMap = userBankDao.selectByPrimaryKey(Integer.valueOf(bankId));
            if (null == bankAllInfoMap) {
                model.addAttribute("bankName", "请选择银行");
            } else {
                model.addAttribute("cardId","");
                model.addAttribute("bankId", bankId);
                model.addAttribute("bankName", bankAllInfoMap.get("bankName"));
                model.addAttribute("bankCard", cardNo);
                model.addAttribute("userPhone", userPhone);
            }
            model.addAttribute("userId", userId);
            User user = userService.searchByUserid(Integer.parseInt(userId));
            model.addAttribute("realName", user.getRealname());
            
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("syskey", "TG_SERVER_BK");
            List<BackConfigParams> list = backConfigParamsService.findParams(params);
            model.addAttribute("tg_path", list.get(0).getSysValue());
            model.addAttribute("orderNo",orderNo);
            model.addAttribute("return_url",return_url);
        } else {
            model.addAttribute("msg", "访问失败");
        }
        return "userinfo/firstUserBank360";
    }


}
